/* Copyright 2007 You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at:
 http://developer.sun.com/berkeley_license.html
 $Id: component.js,v 1.0 2007/04/15 19:39:59 gmurray71 Exp $
*/
jmaki.namespace("jmaki.widgets.jmaki.cart");


jmaki.widgets.jmaki.cart.Widget = function(wargs) {

    var _widget = this; 
    var template; 
    var container;
    var list;
    var items = [];
    var index = 0;
    var count = 3;
    var publish = "/jmaki/cart";
    var subscribe = ['/jmaki/cart'];
    
    var next;
    var prev;
    var showNav = true;

    var data;
    
    var rawItems = [];
    
    var totalDiv = document.getElementById(wargs.uuid + "_total");

    if (wargs.args) {
        if (wargs.args.count) {
            count = Number(wargs.args.count);
        }
        if (typeof wargs.args.showNavigation != 'undefined') {        
            showNav = wargs.args.showNavigation;
            var nav  = document.getElementById(wargs.uuid + "_nav");
            if (nav && showNav == false) nav.style.display = "none";
        }
        
       if (wargs.args.filter) {
           filter = wargs.args.filter;
       }
	
    }
    
    if (wargs.subscribe){
        if (typeof wargs.subscribe == "string") {
            subscribe = [];
            subscribe.push(wargs.subscribe);
        } else {
            subscribe = wargs.subscribe;
        }
    }    
    
    if (wargs.publish){
        publish = wargs.publish;
    }

    this.addCartItem = function(text) {
        var li = document.createElement("li");
        li.innerHTML = text;
        list.appendChild(li);
    }
    
    this.addItem = function(item) {

        if (item.value)item = item.value;
        var quantity = 1;
        // add one to the quantity if it's already there
        for (var _i=0; _i < rawItems.length; _i++) {
              
              if (item.id == rawItems[_i].id) {  
                  jmaki.log("current quantity=" + rawItems[_i].quantity);
                rawItems[_i].quantity += quantity;
                // reset the template
                items[_i] = _widget.applyTemplate(rawItems[_i], template);
                _widget.render();
                return;
              }
        }
        
        if (!item.quantity)item.quantity = 1;
        
        rawItems.push(item);      
        items.push(_widget.applyTemplate(item, template));
        _widget.render();
    }  

    this.render = function() {
        // remove the innerHTML
        list.innerHTML = "";
        for (var _i=index; _i < items.length && _i < (index + count); _i++) {
          _widget.addCartItem(items[_i]);
        }
        if ((index + count) >= items.length) {
            next.style.visibility = "hidden";
        } else {
            next.style.visibility= "visible";
        }
        if (index == 0) {
            prev.style.visibility = "hidden";
        } else {
            prev.style.visibility= "visible";
        }
        var grandTotal = 0;
        for (var _i=0; _i < rawItems.length; _i++) {
            jmaki.log("adding " + rawItems[_i].price + " i=" + jmaki.inspect(rawItems[_i]));
            grandTotal += rawItems[_i].price * rawItems[_i].quantity;
        }
        totalDiv.innerHTML = grandTotal;
    }
    
    this.applyTemplate = function(obj, _t) {
        for (var i in obj) {
            var token = "@{" + i + "}";
            while (_t.indexOf(token) != -1) {
                _t = _t.replace(token, obj[i]);
            }
        }
        return _t;
    }   
    
    this.getNext = function() {
        if (index + count < items.length) index += count;
        _widget.clearList();        
        _widget.render();
    }
    
    this.getPrevious = function() {
        if (index > 0){
            index -= count;
            prev.enabled = "true";
        } else {
            prev.enabled = "false";
            index = 0;
        }
        _widget.clearList();        
        _widget.render();
        
    }
    
    this.clearList = function() {
        for (var i=list.childNodes.length - 1; i > 0 ; i--) {
           list.removeChild(list.childNodes[i]);
        }
    }

    if (wargs.value) {
        data = wargs.value;
        init();
    } else if (wargs.service) {
        jmaki.doAjax({url: wargs.service, callback: function(req) {

                    var _in = eval('(' + req.responseText + ')');
                    if (_in.dataType) {
                        if (_in.dataType == "jmakiRSS") {
                          data = jmaki.filter(_in, filter);
                        }  else {
                          data = _in;
                        }
                    } else {
                        data = _in;
                    }
                    init();
        }});
    } else {
        init();
    }


    function init() {
       // this is the template for all li
       template = unescape(document.getElementById(wargs.uuid + "_template").innerHTML + "");
       for (var _i=index; data && _i < data.length; _i++) {
         items.push(_widget.applyTemplate(data[_i], template));
       }    
       container = document.getElementById(wargs.uuid);
       list = document.getElementById(wargs.uuid + "_list");
       next = document.getElementById(wargs.uuid + "_next");
       prev = document.getElementById(wargs.uuid + "_previous");
       next.onclick = _widget.getNext;
       prev.onclick = _widget.getPrevious;
       _widget.render();
          
  }
    function doSubscribe(topic, handler) {
        var i = jmaki.subscribe(topic, handler);
        _widget.subs.push(i);
    }
    
    this.destroy = function() {
        for (var i=0; _widget.subs && i < _widget.subs.length; i++) {
            jmaki.unsubscribe(_widget.subs[i]);
        }
        delete list;
        delete next;
        delete prev;
        delete container;        
    }

    this.postLoad = function() {     
        // track the subscribers so we can later remove them
        _widget.subs = [];
        for (var _i=0; _i < subscribe.length; _i++) {
            doSubscribe(subscribe[_i]  + "/clear", _widget.clearList);
            doSubscribe(subscribe[_i]  + "/addItem", _widget.addItem);
        }                
    }    
}